<script setup lang="ts">
import { computed, nextTick, onUnmounted, reactive, ref, h } from "vue";
import { standardList, scoreSave } from "@/services/teacher";
import { FormInstance, Message } from "@arco-design/web-vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import Local from "@/utils/local";
import { validateScore } from "@/utils/validation";
import {
  getDetail,
  queryByRegistAndTeacher,
} from "@/services/reviewStatistics";
import useModal from "@/hooks/useModal.ts";
import useScoreStore from "@/stores/modules/useScoreStore.ts";
const props = defineProps({
  registUid: String,
});
// todo 整体优化
const { setScore, getScore } = useScoreStore();

const formRef = ref<FormInstance>();

const loading = ref(false);
const errors = ref<string[]>([]);

const disabled = ref<boolean>(true);

const teacherId: string = JSON.parse(
  Local.localRead("teacher") || "{}"
)!.teacherId;

const emits = defineEmits<{
  (e: "list"): void;
  (e: "updateVariable", value: any): void; // 新增事件，用于传递变量
}>();

const rules = [
  {
    required: true,
    message: "请输入分数",
  },
];

const getScoreRules = (record: any) => {
  return [
    {
      required: true,
      message: "请输入分数",
    },
    {
      validator: (value: number, callback: (error?: string) => void) => {
        if (value > record.standardScore) {
          callback(`分数不能超过${record.standardScore}分`);
        } else {
          callback();
        }
      },
    },
  ];
};

const form = ref([]);
const handleCancel = () => {
  showDrawer.value = false;
  errors.value = [];
};

const uid = ref("");

const tableLoading = ref(false);

const formData = reactive({
  data: [],
});

const getList = () => {
  tableLoading.value = true;
  standardList({
    moduleId: Local.localRead("moduleId"),
  })
    .then((res) => {
      if (res.code === 200) {
        formData.data = res.data.map((item) => ({
          ...item,
          score: "",
        }));
      } else {
        formData.data = [];
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const someVariable = ref(1);

const promise = (url: any, msg: string) => {
  url
    .then((res: any) => {
      if (res.code === 200) {
        Message.success(msg);
        showDrawer.value = false;
        errors.value = [];
        emits("list");
        emits("updateVariable", someVariable);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const list = ref([]);

// 提交时分数至少填写一个
const handleOk = () => {
  formRef.value?.validate().then((v) => {
    console.log(form.value, "listlist ");
    if (!v) {
      loading.value = true;
      list.value = formData.data
        .filter((item) => item.score !== "")
        .map((item) => {
          const formItem = form.value.find((f) => f.standardId === item.id);
          console.log(form.value, "form.valueform.value");

          return {
            // item.id,
            id: formItem ? formItem.id : 0, // 使用查询到的id，如果没有则传0
            teacherId: JSON.parse(Local.localRead("teacher")).teacherId,
            registUid: props.registUid,
            standardId: item.id,
            score: item.score,
          };
        });

      const hasAtLeastOneScore = formData.data.some(
        (item) =>
          item.score !== "" && item.score !== null && item.score !== undefined
      );
      if (!hasAtLeastOneScore) {
        // 如果没有填写任何分数，给出提示并阻止提交
        Message.warning("请至少填写一项分数后再提交");
        loading.value = false;
        return;
      }

      promise(scoreSave(list.value), "保存成功");
    }
  });
};

const show = (id: string, bool) => {
  disabled.value = bool;
  // setScore({})
  uid.value = id;
  loading.value = true;
  nextTick(() => {
    handleDetail();
    getList();
    formRef.value?.clearValidate();
    showDrawer.value = true;
    loading.value = false;
  });
};

const handleDetail = () => {
  queryByRegistAndTeacher({
    registUid: props.registUid,
    teacherId: JSON.parse(Local.localRead("teacher")).teacherId,
  }).then((res) => {
    form.value = res.data.record;
    if (form.value && form.value.length > 0) {
      console.log(formData.data);
      form.value.forEach((formItem) => {
        const dataIndex = formData.data.findIndex(
          (item) => item.id === formItem.standardId
        );
        if (dataIndex !== -1) {
          formData.data[dataIndex].score = formItem.score;
        }
      });
    }
    nextTick(() => {
      const score = formData.data.map((item) => ({
        score: item.score,
      }));

      if (!getScore()[uid.value]) {
        setScore({
          ...getScore(),
          [uid.value]: score,
        });
      }
      console.log(disabled.value);
      formData.data = formData.data.map((item, i) => {
        if (disabled.value) {
          return {
            ...item,
            score: getScore()[uid.value][i].score || score[i].score,
          };
        }
        return {
          ...item,
          score: score[i].score || "",
        };
      });
    });
  });
};

function formatLevel1TextWithBoldIntro(text: string) {
  // 判断是否以编号开头（如 1.、2.）
  // const startsWithNumber = /^\d+\./.test(text);

  const startsWithNumber = /^[1-9]\d*\./.test(text);

  if (startsWithNumber) {
    // 如果以编号开头，只换行，不加粗
    return text.replace(/(\d+\..*?)(?=\d+\.|$)/gs, "<br>$1").trim();
  }

  // 否则，加粗开头部分，换行编号部分
  const regex = /^([^\d]+?)(?=\d+\.)/s;
  const match = text.match(regex);

  if (match) {
    const [, intro] = match;
    const numberedContent = text.substring(intro.length).trim();
    const formattedNumberedContent = numberedContent.replace(
      /(\d+\..*?)(?=\d+\.|$)/gs,
      "<br>$1"
    );
    return `<strong style="font-size: 15px;">${intro.trim()}</strong>${formattedNumberedContent}`;
  }

  if (text.includes("0.5分")) {
    console.log(111);
    return text;
  }

  // 如果没有编号，只加粗并换行
  return `<strong>${text}</strong><br>`;
}

const columns = [
  {
    title: "一级指标",
    key: "name",
    dataIndex: "name",
    width: 150,
  },
  // {
  //   title: "二级指标",
  //   key: "level1",
  //   dataIndex: "level1",
  // },
  {
    title: "分值",
    key: "level1",
    dataIndex: "level1",
    width: 100,
  },
  {
    title: "指标描述",
    dataIndex: "level2",
    slotName: "level2",
  },
  {
    title: "分数",
    key: "score",
    dataIndex: "score",
    slotName: "score",
    width: "100",
  },
];

const spanMethodAll = ({ column, rowIndex, record }) => {
  if (column.dataIndex === "name") {
    const prevRecord = rowIndex > 0 ? formData.data[rowIndex - 1].name : null;
    if (prevRecord && prevRecord === record.name) {
      return { rowspan: 0, colspan: 0 };
    } else {
      const sameNameCount = formData.data.filter(
        (item) => item.name === record.name
      ).length;
      return { rowspan: sameNameCount, colspan: 1 };
    }
  }

  if (column.dataIndex === "level1") {
    const prevRecord = rowIndex > 0 ? formData.data[rowIndex - 1] : null;
    if (
      prevRecord &&
      prevRecord.name === record.name &&
      prevRecord.level1 === record.level1
    ) {
      return { rowspan: 0, colspan: 0 };
    } else {
      const sameNameAndLevel1Count = formData.data.filter(
        (item) => item.name === record.name && item.level1 === record.level1
      ).length;
      return { rowspan: sameNameAndLevel1Count, colspan: 1 };
    }
  }
  if (column.dataIndex === "score") {
    const prevRecord = rowIndex > 0 ? formData.data[rowIndex - 1].name : null;
    if (prevRecord && prevRecord === record.name) {
      return { rowspan: 0, colspan: 0 };
    } else {
      const sameNameCount = formData.data.filter(
          (item) => item.name === record.name
      ).length;
      return { rowspan: sameNameCount, colspan: 1 };
    }
  }
  return { rowspan: 1, colspan: 1 };
};

const showDrawer = ref(false);

defineExpose({
  show,
});

const handleClose = () => {
  console.log(disabled.value);
  if (disabled.value) {
    setScore({
      ...getScore(),
      [uid.value]: formData.data.map((item) => ({ score: item!.score })),
    });
  }
  nextTick(() => {
    console.log(getScore());
  });
};

const total = computed(() => {
  const score = formData.data.map((item) => item?.score || 0);
  const totlaScore: number = score.reduce((acc, cur) => acc + cur, 0);
  return totlaScore.toFixed(2);
});
</script>

<template>
  <a-drawer
    :visible="showDrawer"
    width="50%"
    @ok="handleOk"
    @cancel="handleCancel"
    :ok-loading="loading"
    :mask-closable="true"
    :unmount-on-close="true"
    @close="handleClose"
  >
    <template #title>
      <div>
        <span>评分</span>
        <span>
          （<span style="color: #f5222d">一旦刷新浏览器、退出登录或者关闭浏览器，没有提交的分数将被清空，请及时提交分数</span>）
        </span>
      </div>
    </template>
    <a-form
      :model="formData"
      ref="formRef"
    >
      <a-table
        :loading="loading"
        :data="formData.data"
        :columns="columns"
        :bordered="tableBorder"
        :pagination="false"
        :span-method="spanMethodAll"
      >
        <template #level2="{record}">
          <p v-html="formatLevel1TextWithBoldIntro(record.level2)"></p>
        </template>

        <template #score="{ record, rowIndex }">
          <!-- :rules="rules" -->
          <a-form-item
            :rules="getScoreRules(record)"
            :field="`data[${rowIndex}].score`"
            :hide-asterisk="true"
            :label-col-props="{span: 0}"
          >
            <a-input-number
              v-model="record.score"
              :default-value="record.score"
              :read-only="!disabled"
              :min="0"
              :precision="2"
              style="width: 160px"
              placeholder="请输入分数"
            />
          </a-form-item>
        </template>
      </a-table>
    </a-form>
    <template #footer>
      <div class="modalFooter">
        <span>总分：{{total}}</span>
        <a-button
          v-if="!disabled"
          type="primary"
          @click="disabled = true"
        >修改</a-button>
        <a-space v-else>
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            type="primary"
            @click="handleOk"
          >提交</a-button>
        </a-space>
      </div>
    </template>
  </a-drawer>
</template>

<style scoped lang="scss">
.error-container {
  margin-bottom: 16px;
  padding: 8px;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
}

.error-message {
  color: #f5222d;
  font-size: 12px;
  margin: 4px 0;
}
.modalFooter {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
